﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using H2.NET.Common;
using H2.NET.Web.Workflow.DwzCode;
using H2.NET.Web.Workflow.Helpers;
using Ultimus.OC;
using Ultimus.WFServer;
using UServLib;

namespace H2.NET.Web.Workflow.Workflow
{
    public partial class TaskBack : BasePage
    {
        #region 属性 public

        private DataTable dt = new DataTable();

        [SessionType]
        string strProcessName = "";

        //类型
        public string Type
        {
            get
            {
                return this.ViewState["Type"] == null ? "" : (String)this.ViewState["Type"];
            }
            set
            {
                this.ViewState["Type"] = value;
            }
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            var action = AksRequest.GetQueryStringValue("action");
            if (string.IsNullOrEmpty(action)) //默认页面加载
            {
                try
                {
                    load_gv_inbox_list();
                }
                catch (Exception ee)
                {
                    TaskDB.Log("", false, "调用 TaskBack.aspx 页面 Page_Load 事件出错：" + ee.Message);
                }
            }
            else if (action == "back_selected") //收回选中的任务
            {
                var flag = false;

                var taskIds = AksRequest.GetString("ids");
                var aryTaskIds = string.IsNullOrEmpty(taskIds) ? new string[0] : taskIds.Split(',');
                foreach (var taskId in aryTaskIds)
                {
                    var task = new Task();
                    task.InitializeFromTaskId(taskId);
                    flag = task.TakeBack(clsCmm.comm_username);

                    //追加任务指派记录
                    AssignConferTo(task.strProcessName, task.nIncidentNo.ToString(), task.strStepName, task.strAssignedToUser, task.strAssignedToUserFullName
                                 , clsCmm.comm_username, clsCmm.comm_userfullname, "TakeBack");

                }

                WriteToClient(flag ? "true" : "false");
            }
            else if (action == "future_back") //将来所有的任务收回
            {
                try
                {
                    clsCmm.clsDB.Storage("bpmDB");
                    var count = clsCmm.clsDB.ExcuteSql("delete from assignment where taskuser='" + clsCmm.comm_username + "' and processname is null and stepid is null and steplabel is null and assignuntil is not null");

                    WriteToClient(count >= 1 ? "true" : "false");
                }
                catch
                {
                   WriteToClient("false");
                }
            }
        }
        
        public void load_gv_inbox_list()
        {
            try
            {
                //加载列表
                dt = get_all_inbox();

                //数据合法性检查
                if (dt == null)
                {
                    return;
                }

                #region added by zk 2009-12-21 start
                //取得所有的用户账号对应用户姓名             
                string str_user_name = "";
                DataTable dt2 = new DataTable();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //initiator
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["initiator"].ToString().Trim() + "'";
                    }

                    //taskuser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["taskuser"].ToString().Trim() + "'";
                    }

                    //assignedtouser
                    if (str_user_name.IndexOf(",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'") == -1)
                    {
                        str_user_name += ",'" + dt.Rows[i]["assignedtouser"].ToString().Trim() + "'";
                    }
                }

                //从数据库中查询用户信息
                string strSQL = "select rtrim(FULLNAME) as UserFullName,lower(rtrim(Name)) as UserShortName from JOBS where lower(rtrim(Name)) in('-1'" + str_user_name + ")";
                clsCmm.clsDB.Storage("bpmDB");
                dt2 = clsCmm.clsDB.Query(strSQL);
                #endregion added by zk 2009-12-21 end

                //设置状态列的图片
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //处理表单类型 (自定义表单 & 标准表单)
                    string HelpUrl = dt.Rows[i]["helpurl"].ToString();

                    Dictionary<string, string> parms = new Dictionary<string, string>();
                    parms.Add("taskId", dt.Rows[i]["taskid"].ToString());
                    parms.Add("incident", dt.Rows[i]["incident"].ToString());

                    dt.Rows[i]["openform"] = UltimusHelper.ResolveUrl(dt.Rows[i]["helpurl"].ToString().Trim(),
                                                                    parms,
                                                                    dt.Rows[i]["processname"].ToString().Trim());

                    #region added by zk 2009-12-21 start
                    //循环设置用户信息
                    for (int j = 0; j < dt2.Rows.Count; j++)
                    {
                        //initiator
                        if (dt.Rows[i]["initiator"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["initiator_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //taskuser
                        if (dt.Rows[i]["taskuser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["taskuser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }

                        //assignedtouser
                        if (dt.Rows[i]["assignedtouser"].ToString().ToLower().Trim() == dt2.Rows[j]["UserShortName"].ToString().ToLower().Trim())
                        {
                            dt.Rows[i]["assignedtouser_name"] = dt2.Rows[j]["UserFullName"].ToString().Trim();
                        }
                    }
                    #endregion added by zk 2009-12-21 end

                    //流程状态图标
                    switch (dt.Rows[i]["substatus"].ToString().Trim())
                    {
                        case "0":
                        case "1":
                            dt.Rows[i]["img_status"] = "frm_inbox_late.gif";
                            break;

                        case "2":
                            dt.Rows[i]["img_status"] = "frm_inbox_overdue.gif";
                            break;

                        case "3":
                            dt.Rows[i]["img_status"] = "frm_inbox_urgent.gif";
                            break;

                        case "4":
                            dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                            break;

                        case "7":
                            dt.Rows[i]["img_status"] = "frm_inbox_urgent.gif";
                            break;

                        case "8":
                            dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                            break;

                        case "16":
                            dt.Rows[i]["img_status"] = "frm_inbox_returned.gif";
                            break;

                        case "32":
                            dt.Rows[i]["img_status"] = "frm_inbox_resubmitted.gif";
                            break;

                        default:
                            dt.Rows[i]["img_status"] = "frm_initiate_blank.gif";
                            break;
                    }

                    //判断是否为指派、会办的任务类型
                    if (dt.Rows[i]["taskuser"].ToString() != dt.Rows[i]["assignedtouser"].ToString())
                    {
                        dt.Rows[i]["img_status"] = "frm_inbox_reassigned.gif";
                    }

                    //是否显示监控图标
                    if (dt.Rows[i]["taskid"] == DBNull.Value || dt.Rows[i]["taskid"].ToString().Trim() == "")
                    {
                        dt.Rows[i]["img_monitor"] = "frm_initiate_blank.gif";
                        dt.Rows[i]["img_status"] = "frm_initiate_blank.gif";
                    }
                    else
                    {
                        dt.Rows[i]["img_monitor"] = "bpmview.gif";
                    }

                }

                //第一次没有排序字段的情况
                if (ViewState["OrderBy"] == null)
                {
                    dt.DefaultView.Sort = "starttime DESC";
                }
                else
                {
                    dt.DefaultView.Sort = ViewState["OrderBy"] + " " + ViewState["Order"];
                }

                gvInbox.DataSource = dt;
                gvInbox.DataBind();

            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 load_gv_inbox_list 方法出错：" + ee.Message);
            }
        }

        public DataTable get_all_inbox()
        {
            try
            {
                string strSQL = "";
                string strUserName = clsCmm.comm_username;
                string strSummary = ""; //tb_Summary.Text.Trim().Replace(",", "',").Replace("'", "''");
                string strIncidentNoFrom = "";// txtIncidentFrom.Text.Trim().Replace(".", "");
                string strIncidentNoTo = "";// txtIncidentTo.Text.Trim().Replace(".", "");

                //查询过滤中Process下拉列表中的值
                string strProcess = "all";
                //if (drpProcess.SelectedItem != null)
                //{
                //    strProcess = drpProcess.SelectedItem.Value.Trim();
                //}

                //string strStep = "all";
                //if (drpStep.SelectedItem != null)
                //{
                //    strStep = drpStep.SelectedItem.Value.Trim();
                //}

                //查找收件箱列表
                strSQL = "";
                strSQL += "select distinct d.*,";
                strSQL += "       '' as initiator_name,";
                strSQL += "       '' as taskuser_name,";
                strSQL += "       '' as assignedtouser_name";
                strSQL += "  from (select b.*, c.summary, c.priority, c.initiator";
                strSQL += "          from (select rtrim(a.taskid) as taskid";
                //中文的情况，流程名变化
                if (clsCmm.comm_language == "en-us" && Util.AppSettings("language").ToLower() == "yes")
                {
                    strSQL += " ,h.processhelpurl as processname3";
                    strSQL += " ,h.processname";
                }
                else
                {
                    strSQL += " ,a.processname as processname3";
                    strSQL += " ,a.processname";
                }

                strSQL += " ,rtrim(a.helpurl) as helpurl";
                strSQL += " ,'' as openform";

                strSQL += " ,a.incident";
                strSQL += " ,a.steplabel";
                strSQL += " ,a.taskuser";
                strSQL += " ,a.assignedtouser";
                strSQL += " ,'' as img_status";     //状态图标
                strSQL += " ,'' as img_monitor";    //监控图标
                strSQL += " ,a.status";
                strSQL += " ,a.substatus";
                strSQL += " ,a.starttime";
                strSQL += " ,a.delaytime";
                strSQL += " ,a.overduetime";
                strSQL += " ,a.urgentduetime";

                strSQL += " from tasks a WITH (NOLOCK) , initiate h WITH (NOLOCK) ";    //with(readpast,rowlock)
                strSQL += " where 1=1 and a.processname=h.processname AND H.PROCESSNAME IN(SELECT [PROCESSNAME] FROM [PROCESSES] WHERE [PROCESSES].[DESCRIPTION] IN (SELECT KeyWords FROM BPMSYSTEM WHERE Platform = '" + Util.AppSettings("platform") + "')) ";
                strSQL += " and a.taskid not in(select taskid from taskqueue)";

                //task back
                strSQL += " and lower(a.taskuser) = lower('" + strUserName + "')";
                strSQL += " and lower(a.assignedtouser) <> lower('" + strUserName + "')";
                strSQL += " and a.status = 1";
                
                //如果 Type=1 的情况,则表示我的审批   Type=2 的情况,则表示我的申请
                if (this.Type == "1")
                {
                    strSQL += " and right(rtrim(a.stepid),1) <> 'B'";
                }
                else if (this.Type == "2")
                {
                    strSQL += " and right(rtrim(a.stepid),1) = 'B'";
                }


                //查询过滤
                if (strProcess != "all")
                {
                    strSQL = strSQL + " and a.processname = '" + strProcess + "'";
                }

                //added by
                if (!string.IsNullOrEmpty(strProcessName))
                {
                    strSQL = strSQL + " and a.processname = '" + strProcessName + "'";
                }

                //if (strStep != "all")
                //{
                //    strSQL = strSQL + " and a.steplabel = '" + strStep + "'";
                //}

                if (strIncidentNoFrom != "")
                {
                    strSQL = strSQL + " and a.incident >= " + strIncidentNoFrom + "";
                }

                if (strIncidentNoTo != "")
                {
                    strSQL = strSQL + " and a.incident <= " + strIncidentNoTo + "";
                }

                strSQL += " ) b";
                strSQL += " left join incidents c on b.processname = c.processname";
                strSQL += " and b.incident = c.incident) d";

                //摘要
                if (strSummary != "")
                {
                    strSQL = strSQL + " where d.summary like '%" + strSummary + "%'";
                }

                TaskDB.Log("", true, "调用 inbox.aspx 页面 get_all_inbox 方法SQL：" + strSQL);
                clsCmm.clsDB.Storage("bpmDB");
                dt = clsCmm.clsDB.Query(strSQL);

                return dt;
            }
            catch (Exception ee)
            {
                TaskDB.Log("", false, "调用 inbox.aspx 页面 get_all_inbox 方法出错：" + ee.Message);
                return null;
            }
        }

        private void AssignConferTo(string strProcess, string strIncident, string strStep, string strUserName, string strUserFullName, string strAssignedToUserName, string strAssignedToUserFullName, string strAssignedClass)
        {
            try
            {
                clsCmm.clsDB.Storage("oleDB");
                var dt = clsCmm.clsDB.Query("select * from t_AssignedTo where Process='" + strProcess + "' and Incident=" + strIncident + " and Step='" + strStep + "' and Time is null");
                if (dt.Rows.Count >= 1)
                {
                    var i = clsCmm.clsDB.ExcuteSql("update t_AssignedTo set Time=getdate() where Process='" + strProcess + "' and Incident=" + strIncident + " and Step='" + strStep + "' and Time is null");
                }

                var strInsert = "insert into t_AssignedTo(ID,Process,Incident,Step,UserName,UserFullName,AssignedToUserName,AssignedToUserFullName,AssignedClass,StartTime) values('"
                      + System.DateTime.Now.ToString("yyyyMMddHHmmss") + dt.GetHashCode().ToString() + "'"
                      + ",'" + strProcess + "'"
                      + "," + strIncident
                      + ",'" + strStep + "'"
                      + ",'" + strUserName + "'"
                      + ",'" + strUserFullName + "'"
                      + ",'" + strAssignedToUserName + "'"
                      + ",'" + strAssignedToUserFullName + "'"
                      + ",'" + strAssignedClass + "'"
                      + ",getdate()"
                      + ")";

                clsCmm.clsDB.ExcuteSql(strInsert);
            }
            catch (Exception ex)
            {

            }
        }

        public bool is_future_task_has_assigned()
        {
            try
            {
                int intCNT = 0;
                string strSQL = "select count(*) as cnt from assignment where taskuser='" + clsCmm.comm_username + "' and processname is null and stepid is null and steplabel is null and assignuntil is not null";
                clsCmm.clsDB.Storage("bpmDB1");
                dt = clsCmm.clsDB.Query(strSQL);

                //如果结果返回值 > 1 的情况，返回 true，否则返回 false
                int.TryParse(dt.Rows[0]["cnt"].ToString(), out intCNT);
                if (intCNT >= 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                //Logger.Error("调用 inbox.aspx 页面 is_future_task_has_assigned方法出错：" + ee.Message);
                return false;
            }
        }
    }
}